package ca.camosun.inventory;

import android.app.Activity;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class SearchActivity extends ListActivity {
	public static final String TAG = SearchActivity.class.getSimpleName();
	
	public SearchActivity(){
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
		
		Intent queryIntent = getIntent();
		String queryAction = queryIntent.getAction();
		if (Intent.ACTION_SEARCH.equals(queryAction)) {
			this.doSearch(queryIntent);
		} else if (Intent.ACTION_VIEW.equals(queryAction)) {
			this.doView(queryIntent);
		} else {
			Log.d(TAG, "Create intent not from search");
		}
	}
	
	public void onNewIntent(Intent queryIntent) {
		super.onNewIntent(queryIntent);
		String queryAction = queryIntent.getAction();
		if(Intent.ACTION_SEARCH.equals(queryAction)) {
			this.doView(queryIntent);
		}
	}
	
	private void doView(Intent queryIntent) {
		Uri uri = queryIntent.getData();
		String action = queryIntent.getAction();
		Intent intent = new Intent (action);
		intent.setData(uri);
		startActivity(intent);
		
	}

	private void doSearch(Intent queryIntent) {
		String queryString = queryIntent.getDataString();
		Intent intent = getIntent();
		Bundle appData = new Bundle();
		
		if(Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
		}
		
		// display results
		appData.putString("user query", queryString);
		intent.setData(Uri.fromParts("", "", queryString));
		intent.setAction(Intent.ACTION_SEARCH);
		queryIntent.putExtras(appData);
		startActivity(intent);
	}
	
	@Override
	public boolean onSearchRequested() {
		startSearch("default-search", true, null, false);
		return true;
		
	}
}
